﻿
using WCYCReader.Main;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Windows;
using WCYCReader.Utility;
namespace WCYCReader.Main.Core
{
    public class HttpPostClient
    {
        private StringBuilder _postData = new StringBuilder();

        private WebHeaderCollection _header = new WebHeaderCollection();

        public HttpPostClient(string parameters)
        {
            this._postData.Append(parameters);
        }

        public HttpPostClient(IList<string> parameters)
        {
            foreach (string parameter in parameters)
            {
                this._postData.Append(string.Format("{0}&", parameter));
            }
        }

        public HttpPostClient(IDictionary<string, string> parameters)
        {
            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                this._postData.Append(string.Format("{0}={1}&", parameter.Key, parameter.Value));
            }
        }

        public HttpPostClient(IDictionary<string, string> parameters, WebHeaderCollection whc)
        {
            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                this._postData.Append(string.Format("{0}={1}&", parameter.Key, parameter.Value));
            }
            if (whc != null)
            {
                this._header = whc;
            }
        }

        public HttpPostClient(WebHeaderCollection whc)
        {
            if (whc != null)
            {
                this._header = whc;
            }
        }

        public void DownloadStringAsync(Uri address)
        {
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(address);
                if (this._header != null)
                {
                    httpWebRequest.Headers = this._header;
                }
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                httpWebRequest.BeginGetRequestStream(new AsyncCallback(this.RequestReady), httpWebRequest);
            }
            catch
            {
                if (this.DownloadStringCompleted != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                    });
                }
            }
        }

        private void RequestReady(IAsyncResult asyncResult)
        {
            HttpWebRequest asyncState = asyncResult.AsyncState as HttpWebRequest;
            if (this._postData.ToString().Length > 0)
            {
                using (Stream stream = asyncState.EndGetRequestStream(asyncResult))
                {
                    using (StreamWriter streamWriter = new StreamWriter(stream))
                    {
                        string str = this._postData.ToString();
                        str = str.Substring(0, str.Length - 1);
                        streamWriter.Write(str.ToString());
                        streamWriter.Flush();
                    }
                }
            }
            asyncState.BeginGetResponse(new AsyncCallback(this.ResponseReady), asyncState);
        }

        private void ResponseReady(IAsyncResult asyncResult)
        {
            HttpWebRequest asyncState = asyncResult.AsyncState as HttpWebRequest;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebResponse = (HttpWebResponse)asyncState.EndGetResponse(asyncResult);
                string empty = string.Empty;
                using (Stream responseStream = httpWebResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream))
                    {
                        empty = streamReader.ReadToEnd();
                    }
                }
                if (!SettingHelper.IsSettings("QQReader_sid"))
                {
                    WebHeaderCollection headers = httpWebResponse.Headers;
                    if (headers["sid"] != null)
                    {
                        SettingHelper.SaveInToSettings("QQReader_sid", headers["sid"]);
                    }
                }
                if (this.DownloadStringCompleted != null)
                {
                    this.DownloadStringCompleted(this, new DownloadStringCompletedEventArgs(empty));
                }
            }
            catch
            {
                if (this.DownloadStringCompleted != null)
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => Prompt.PromptMessage("提示：网络异常！"));
                }
            }
        }

        public event HttpPostClient.DownloadStringCompletedHandler DownloadStringCompleted;

        public delegate void DownloadStringCompletedHandler(object sender, DownloadStringCompletedEventArgs e);
    }
}

